package com.xindaoapp.happypet.fragments;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.ExchangeResult;
import com.xindaoapp.happypet.bean.GoodsRecord;
import com.xindaoapp.happypet.bean.NiuniuRecord;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;

/**
 * 我的记录
 * 
 * @author xindaoapp
 * 
 */
public class MyRecordFragment extends BaseFragment implements OnClickListener {


    private RelativeLayout mNoData, mNoData2;

    private ViewPager mPager;
    private PullToRefreshListView mPullToRefreshListView, mPullToRefreshListView2;
    private View view1, view2;
    private List<View> mViews;

    private RelativeLayout tab1, tab2;
    private ImageView iv_niuniu, iv_duihuan;
    private TextView tv_niuniu, tv_duihuan;

    private List<NiuniuRecord> mNiuRecord = null;
    private List<GoodsRecord> mGoodsRecord = null;

    private RelativeLayout mNoNet;

    private ConnectionChangeReceiver mChangeReceiver;

    // 虚拟
    private final String[] dates = new String[] {"2014-09-01", "2014-09-01", "2014-09-01"};
    private final String[] opts = new String[] {"每日签到", "每日签到", "每日签到"};
    private final String[] nius = new String[] {"+1", "+1", "+1"};



    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_myrecord, container, false);
    }

    @Override
    protected void initEvents(View view) {
        super.initEvents(view);
    }

    @Override
    protected boolean showRightView() {
        return false;
    };

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        tab1 = (RelativeLayout) view.findViewById(R.id.tab_1);
        tab2 = (RelativeLayout) view.findViewById(R.id.tab_2);
        tab1.setOnClickListener(this);
        tab2.setOnClickListener(this);

        iv_niuniu = (ImageView) view.findViewById(R.id.niuniubi_img);
        iv_duihuan = (ImageView) view.findViewById(R.id.duihuan_img);
        tv_niuniu = (TextView) view.findViewById(R.id.niuniubi_content);
        tv_duihuan = (TextView) view.findViewById(R.id.duihuan_content);

        // iv_niuniu.setOnClickListener(this);
        // iv_duihuan.setOnClickListener(this);
        // tv_niuniu.setOnClickListener(this);
        // tv_duihuan.setOnClickListener(this);

        mNoNet = (RelativeLayout) view.findViewById(R.id.no_net);


        mViews = new ArrayList<View>();
        mPager = (ViewPager) view.findViewById(R.id.viewpager);

        view1 =
                LayoutInflater.from(getActivity()).inflate(R.layout.fragment_myrecord_niuniubi,
                        null);
        view2 =
                LayoutInflater.from(getActivity()).inflate(R.layout.fragment_myrecord_niuniubi,
                        null);

        mViews.add(view1);
        mViews.add(view2);

        mPager.setOnPageChangeListener(mChangeListener);
        mPager.setAdapter(new MyViewPagerAdapter());



        mNoData = (RelativeLayout) view1.findViewById(R.id.no_data);
        mPullToRefreshListView = (PullToRefreshListView) view1.findViewById(R.id.listview);
        mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        mPullToRefreshListView.setOnRefreshListener(mOnRefreshListener);

        // mPullToRefreshListView.setAdapter(new MyAdapter());

        mNoData2 = (RelativeLayout) view2.findViewById(R.id.no_data);
        mPullToRefreshListView2 = (PullToRefreshListView) view2.findViewById(R.id.listview);
        mPullToRefreshListView2.setMode(Mode.PULL_FROM_START);
        mPullToRefreshListView2.setOnRefreshListener(mOnRefreshListener);
        mPullToRefreshListView2.getRefreshableView().setOnItemClickListener(mOnItemClickListener);
        mPullToRefreshListView2.getRefreshableView().setOnItemLongClickListener(
                mOnItemLongClickListener);

        // mPullToRefreshListView2.setAdapter(new MyAdapter2());
        // getActivity().registerReceiver(mAudioButtonJpush,
        // new IntentFilter(Constants.ACTION_AUDIO_SETTING_CHANGED));

        // onLoadData();
    }

    private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // MessageCenterInfo info = (MessageCenterInfo) parent.getAdapter().getItem(position);

        }
    };

    private final OnItemLongClickListener mOnItemLongClickListener = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(final AdapterView<?> arg0, View arg1, final int arg2,
                long arg3) {
            // TODO Auto-generated method stub


            if ("已取消".equals(mGoodsRecord.get(arg2 - 1).exchangetitle)) {
                return false;
            }
            new AlertDialog.Builder(getActivity()).setTitle("温馨提示").setMessage("确定取消兑换本商品么 ?")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();

                            getMoccaApi().getQuxiaoExchangeResult(
                                    mGoodsRecord.get(arg2 - 1).integral_id,
                                    new IRequest<ExchangeResult>() {

                                        @Override
                                        public void request(ExchangeResult t) {
                                            // TODO Auto-generated method stub
                                            if (null != t) {
                                                if (t.result.equals("0")) {
                                                    Toast.makeText(
                                                            getActivity().getApplicationContext(),
                                                            t.msg, Toast.LENGTH_SHORT).show();


                                                    CommonUtil.refurshWeiba(getActivity());
                                                    // 刷新页面
                                                    onLoadData();


                                                } else {
                                                    Toast.makeText(
                                                            getActivity().getApplicationContext(),
                                                            t.msg, Toast.LENGTH_SHORT).show();
                                                }
                                            } else {

                                                try {
                                                    Toast.makeText(
                                                            getActivity().getApplicationContext(),
                                                            R.string.net_error, Toast.LENGTH_SHORT)
                                                            .show();
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }

                                    });
                        }
                    }).create().show();

            return false;
        }
    };


    private final OnPageChangeListener mChangeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
            // TODO Auto-generated method stub
            changeTabBg(arg0);
        }

        private void changeTabBg(int arg0) {
            // TODO Auto-generated method stub
            if (arg0 == 0) {
                iv_duihuan.setBackgroundResource(R.drawable.myrecord_tab2);
                iv_niuniu.setBackgroundResource(R.drawable.myrecord_tab1_select);
                tv_duihuan.setTextColor(Color.parseColor("#666666"));
                tv_niuniu.setTextColor(Color.parseColor("#ff7d90"));
            } else {
                iv_duihuan.setBackgroundResource(R.drawable.myrecord_tab2_select);
                iv_niuniu.setBackgroundResource(R.drawable.myrecord_tab1);
                tv_niuniu.setTextColor(Color.parseColor("#666666"));
                tv_duihuan.setTextColor(Color.parseColor("#ff7d90"));
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub

        }
    };

    private final OnRefreshListener<ListView> mOnRefreshListener =
            new OnRefreshListener<ListView>() {

                @Override
                public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                    onLoadData();
                }
            };

    @Override
    protected void onLoadData() {
        super.onLoadData();
        // mNoData.setVisibility(View.VISIBLE);
        // mNoData2.setVisibility(View.VISIBLE);
        // mPager.getCurrentItem();

        if (!CommonUtil.checkNetState(getActivity())) {

            mNoNet.setVisibility(View.VISIBLE);

            Toast.makeText(getActivity().getApplicationContext(), "当前网络异常 , 请检查网络 !", 1).show();

            HappyPetApplication.mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    mPullToRefreshListView.onRefreshComplete();
                    mPullToRefreshListView2.onRefreshComplete();
                }
            }, 300);

        }



        /**
         * 牛币记录
         */
        getMoccaApi().getNiuniuRecord(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                new IRequest<List<NiuniuRecord>>() {

                    @Override
                    public void request(List<NiuniuRecord> t) {
                        if (t != null) {
                            mNiuRecord = t;

                            onDataArrived(true);
                            if (t.size() == 0) {
                                mNoData.setVisibility(View.VISIBLE);
                            } else {
                                mPullToRefreshListView.setAdapter(new MyAdapter(mNiuRecord));
                                mNoData.setVisibility(View.GONE);
                            }
                        } else {
                            // mNoData.setVisibility(View.VISIBLE);
                            onDataArrived(false);
                        }
                        mPullToRefreshListView.onRefreshComplete();
                    }
                });

        /**
         * 兑换商品记录
         */
        getMoccaApi().getGoodsRecord(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                new IRequest<List<GoodsRecord>>() {
                    @Override
                    public void request(List<GoodsRecord> t) {
                        if (t != null) {
                            mGoodsRecord = t;

                            onDataArrived(true);
                            if (t.size() == 0) {
                                mNoData2.setVisibility(View.VISIBLE);
                            } else {
                                mPullToRefreshListView2.setAdapter(new MyAdapter2(mGoodsRecord));
                                mNoData2.setVisibility(View.GONE);
                            }

                        } else {
                            // mNoData2.setVisibility(View.VISIBLE);
                            onDataArrived(false);
                        }

                        mPullToRefreshListView2.onRefreshComplete();
                    }
                });

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mChangeReceiver);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        mChangeReceiver = new ConnectionChangeReceiver();
        getActivity().registerReceiver(mChangeReceiver,
                new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
    }

    @Override
    protected String getTitleName() {
        return "我的记录";
    }



    @Override
    protected boolean showBackButton() {
        return true;
    }

    class ReceiveJpush extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            onLoadData();
        }

    }


    class MyAdapter extends BaseAdapter {

        List<NiuniuRecord> list = null;

        public MyAdapter(List<NiuniuRecord> niu) {
            super();
            this.list = niu;
        }

        @Override
        public int getCount() {

            return list.size() + 1;
        }

        @Override
        public Object getItem(int position) {

            return null;
        }

        @Override
        public long getItemId(int position) {

            return 0;
        }

        @Override
        public View getView(int position, View contentView, ViewGroup arg2) {

            ViewHolder holder;

            if (position == 0) {
                contentView = View.inflate(mActivity, R.layout.item_myrecord_head, null);
            } else {

                if (contentView == null) {
                    holder = new ViewHolder();
                    contentView = View.inflate(mActivity, R.layout.item_myrecord, null);
                    contentView.setTag(holder);
                    holder.tv_date = (TextView) contentView.findViewById(R.id.tv_date);
                    holder.tv_opt = (TextView) contentView.findViewById(R.id.tv_opt);
                    holder.tv_niuniubi = (TextView) contentView.findViewById(R.id.tv_niuniubi);
                } else {
                    holder = (ViewHolder) contentView.getTag();
                }
                NiuniuRecord niuniu = list.get(position - 1);
                holder.tv_date.setText(niuniu.addtime);
                holder.tv_opt.setText(niuniu.type);
                holder.tv_niuniubi.setText(niuniu.extcredits2);

            }


            return contentView;
        }

        class ViewHolder {
            private TextView tv_date, tv_opt, tv_niuniubi;
        }

    }

    class MyAdapter2 extends BaseAdapter {

        List<GoodsRecord> list = null;

        public MyAdapter2(List<GoodsRecord> goods) {
            super();
            this.list = goods;
        }

        @Override
        public int getCount() {

            return list.size();
        }

        @Override
        public Object getItem(int position) {

            return null;
        }

        @Override
        public long getItemId(int position) {

            return 0;
        }

        @Override
        public View getView(int position, View contentView, ViewGroup arg2) {

            ViewHolder holder;

            if (contentView == null) {
                contentView = View.inflate(mActivity, R.layout.item_myrecord_duihuan, null);
                holder = new ViewHolder();
                // holder.tv_line = (TextView) contentView.findViewById(R.id.tv_line);
                holder.icon = (ImageView) contentView.findViewById(R.id.icon);
                holder.tv_name = (TextView) contentView.findViewById(R.id.tv_name);
                holder.tv_jifen = (TextView) contentView.findViewById(R.id.tv_jifen);
                holder.tv_time = (TextView) contentView.findViewById(R.id.tv_time);
                holder.tv_status = (TextView) contentView.findViewById(R.id.tv_status);
                contentView.setTag(holder);
            } else {
                holder = (ViewHolder) contentView.getTag();
                // holder.iv_good.setImageResource(R.drawable.actionbar_back_indicator);
            }

            // if (position == 0) {
            // holder.tv_line.setVisibility(View.VISIBLE);
            // }

            GoodsRecord goods = list.get(position);
            ImageLoader.getInstance().displayImage(goods.goods_thumb, holder.icon);
            holder.tv_name.setText(goods.goods_name);
            holder.tv_jifen.setText(goods.exchange_integral + "尾巴币");
            holder.tv_time.setText(goods.updatetime);


            holder.tv_status.setText(goods.exchangetitle);


            return contentView;
        }

        class ViewHolder {
            ImageView icon;
            TextView tv_jifen, tv_status, tv_name, tv_time, tv_line;

        }

    }



    class MyViewPagerAdapter extends PagerAdapter {


        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mViews.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(View view, int position, Object object) {
            ((ViewPager) view).removeView(mViews.get(position));
        }

        @Override
        public Object instantiateItem(View view, int position) {
            ((ViewPager) view).addView(mViews.get(position), 0);
            return mViews.get(position);
        }

    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        int id = arg0.getId();
        switch (id) {
            case R.id.tab_1:
                mPager.setCurrentItem(0);
                break;
            case R.id.tab_2:
                mPager.setCurrentItem(1);
                break;

            default:
                break;
        }
    }


    class ConnectionChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {


            if (CommonUtil.isNetworkAvailable(context) == 0) {
                // unconnect network
                Toast.makeText(context, "网络断开连接，请检查网络......", Toast.LENGTH_LONG).show();
                mNoNet.setVisibility(View.VISIBLE);
            } else {
                // Toast.makeText(context, "网络连接上了", Toast.LENGTH_LONG).show();
                // refresh data
                mNoNet.setVisibility(View.GONE);
                onLoadData();

            }
        }
    }

    OnScrollListener mOnScrollListener1 = new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView arg0, int arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub

        }
    };

    OnScrollListener mOnScrollListener2 = new OnScrollListener() {
        boolean mBusy;
        boolean isLoad;

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            {

                switch (scrollState) {
                    case OnScrollListener.SCROLL_STATE_IDLE: // Idle态，进行实际数据的加载显示
                        mBusy = false;

                        if (!mBusy && isLoad) {
                            // jiazai
                        }


                        break;
                    case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                        mBusy = true;
                        break;
                    case OnScrollListener.SCROLL_STATE_FLING:
                        mBusy = true;
                        break;
                    default:
                        break;
                }
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {
            // TODO Auto-generated method stub
            if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount > 0) {
                isLoad = true;
            }

        }
    };
}
